import {
  userLoginReq,
  getUserListReq,
  editUserStatusReq,
  editUserRoleReq,
  addOrEditUserReq,
  deleteUserReq,
} from '../request/user'

const actions = {
  // 用户登录
  async userLogin(context, userInfo) {
    try {
      const userLoginData = await userLoginReq(userInfo)
      context.commit('INIT_USERINFO', userLoginData)
      return userLoginData
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 获取用户列表
  async getUserList(context, params) {
    const userListData = await getUserListReq(params)
    userListData.users.forEach(
      user => (user.dateTime = new Date(user.create_time).toLocaleString())
    )
    context.commit('GET_USER_LIST', userListData)
  },
  // 修改用户状态
  async editUserStatus(context, params) {
    try {
      const { uId, type } = params
      const userStatusData = await editUserStatusReq(uId, type)
      return userStatusData
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 为用户分配角色
  async editUserRole(context, { id, rid }) {
    try {
      const editUserRoleData = await editUserRoleReq(id, rid)
      return editUserRoleData
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 添加或编辑用户
  async addOrEditUser(context, { id, user }) {
    try {
      const addOrEditUserData = await addOrEditUserReq(id, user)
      return addOrEditUserData
    } catch (error) {
      return Promise.reject(error)
    }
  },
  // 批量删除用户
  async deleteUser(context, delUserList) {
    const arr = []
    delUserList.forEach(user => {
      arr.push(deleteUserReq(user.id))
    })
    try {
      const delUserData = await Promise.all(arr)
      return delUserData
    } catch (error) {
      return Promise.reject(error)
    }
  },
}
const mutations = {
  // 初始化用户信息
  INIT_USERINFO(state, userInfo) {
    state.userInfo = userInfo
  },
  GET_USER_LIST(state, userListData) {
    state.userListData = userListData
  },
}
const state = {
  userInfo: null, // 用户信息
  userListData: { users: [] }, // 用户列表
}

export default {
  namespaced: true,
  actions,
  mutations,
  state,
}
